package com.example.templateapp.util

import java.text.SimpleDateFormat
import java.util.*

object DateFormatUtils {
    const val DATE_FORMAT_PATTERN_YMD = "yyyy-MM-dd"
    const val DATE_FORMAT_PATTERN_YMD_HM = "yyyy-MM-dd HH:mm"
    const val DATE_FORMAT_PATTERN_YMD_HM_SS = "yyyy-MM-dd HH:mm:ss"


    /**
     * 时间戳转字符串
     *
     * @param timestamp     时间戳
     * @param isPreciseTime 是否包含时分
     * @return 格式化的日期字符串
     */
    fun long2Str(timestamp: Long, isPreciseTime: Boolean): String {
        return long2Str(timestamp, getFormatPattern(isPreciseTime))
    }

    fun long2Str(timestamp: Long, pattern: String): String {
        return SimpleDateFormat(pattern, Locale.CHINA).format(Date(timestamp))
    }

    fun long2Str(timestamp: Long): String {
        return SimpleDateFormat(DATE_FORMAT_PATTERN_YMD_HM_SS, Locale.CHINA).format(Date(timestamp))
    }

    /**
     * 字符串转时间戳
     *
     * @param dateStr       日期字符串
     * @param isPreciseTime 是否包含时分
     * @return 时间戳
     */
    fun str2Long(dateStr: String, isPreciseTime: Boolean): Long {
        return str2Long(dateStr, getFormatPattern(isPreciseTime))
    }

    fun str2Long(dateStr: String, pattern: String): Long {
        try {
            return SimpleDateFormat(pattern, Locale.CHINA).parse(dateStr)!!.time
        } catch (ignored: Throwable) {
        }
        return 0
    }

    private fun getFormatPattern(showSpecificTime: Boolean): String {
        return if (showSpecificTime) {
            DATE_FORMAT_PATTERN_YMD_HM
        } else {
            DATE_FORMAT_PATTERN_YMD
        }
    }

    private val MONTH_ARRAY =
        arrayOf("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月")

    fun getLastMonthStrArray(amount: Int): Array<String> {
        val result = mutableListOf<String>()
        val calendar = Calendar.getInstance()
        for (index in 0 until amount) {
            result.add(MONTH_ARRAY[calendar.get(Calendar.MONTH)])
            calendar.add(Calendar.MONTH, -1)
        }
        result.reverse()
        return result.toTypedArray()
    }
}